﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using System.IO;
using ExcelDataReader;

namespace CDDY_VehicleRepo
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
            btnSearch_Click(null, null);
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            string strKey = txtVehicle.Text.Trim();

            BindVehicleInfo(strKey);
        }

        private void btnView_Click(object sender, EventArgs e)
        {
            if (dgVehicleRepo.SelectedRows.Count == 0)
            {
                MessageBox.Show("请选中要查看的车辆型号！");
                return;
            }

            string strID = dgVehicleRepo.SelectedRows[0].Cells[0].Value.ToString();

            if (string.IsNullOrEmpty(strID) == false)
            {
                FrmVehicleInfo frmVehicleTypeDetail = new FrmVehicleInfo("View", strID);
                frmVehicleTypeDetail.ShowDialog();
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            FrmVehicleInfo frmVehicleTypeDetail = new FrmVehicleInfo("Add", "");
            frmVehicleTypeDetail.ShowDialog();
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (dgVehicleRepo.SelectedRows.Count == 0)
            {
                MessageBox.Show("请选中要修改的车辆型号！");
                return;
            }

            string strID = dgVehicleRepo.SelectedRows[0].Cells[0].Value.ToString();

            if (string.IsNullOrEmpty(strID) == false)
            {
                FrmVehicleInfo frmVehicleTypeDetail = new FrmVehicleInfo("Update", strID);
                frmVehicleTypeDetail.ShowDialog();
            }
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            FileStream fs = null;
            try
            {
                string strTempPath = string.Empty;
                OpenFileDialog dialog = new OpenFileDialog();
                dialog.Multiselect = false;//该值确定是否可以选择多个文件
                dialog.Title = "请选择模板库";
                dialog.Filter = "模板库(*.xls,*.xlsx)|*.xls;*.xlsx";
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    strTempPath = dialog.FileName;

                    string strExt = Path.GetExtension(strTempPath);

                    IExcelDataReader excelReader= null;
                    fs = new FileStream(strTempPath, FileMode.Open, FileAccess.Read, FileShare.None);
                    if(strExt == ".xls")
                    {
                        excelReader = ExcelReaderFactory.CreateBinaryReader(fs);
                    }
                    else if(strExt == ".xlsx")
                    {
                        excelReader = ExcelReaderFactory.CreateOpenXmlReader(fs);
                    }

                    var vLst = new List<VehicleRepository>();
                    int i = 0;
                    do
                    {
                        while (excelReader.Read())
                        {
                            if(i!=0)
                            {
                                var vehicleRepository = GetVehicleFromReader(excelReader);
                                vLst.Add(vehicleRepository);
                            }
                            i++;
                        }
                    }
                    while (excelReader.NextResult());

                    for (int k = 0; k < vLst.Count; k++)
                    {
                        this.SaveVehicleRepository(vLst[k]);
                    }

                    fs.Close();

                    MessageBox.Show("导入成功！");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
            }
            finally
            {
                if (fs != null)
                {
                    fs.Dispose();
                }
            }
        }

        /// <summary>
        /// 插入一条记录
        /// </summary>
        /// <param name="SaveVehicleRepository"></param>
        private void SaveVehicleRepository(VehicleRepository vehicleRepository)
        {
            try
            {
                var vConfig = Common.GetAppConfig();
                string strSql = "select count(*) from VehicleRepository where vehiclemodel='" + vehicleRepository._vehiclemodel + "'";

                string strValue = DbHelper.GetValue(vConfig[0], strSql);

                if (Convert.ToInt32(strValue) == 0)
                {
                    strSql = " INSERT INTO[dbo].[VehicleRepository] ";
                    strSql += "(";
                    strSql += "[vehiclemodel]";
                    strSql += ",[sb]";
                    strSql += ",[sccmc]";
                    strSql += ",[sccdz]";
                    strSql += ",[hdzkrs]";
                    strSql += ",[bsxxs]";
                    strSql += ",[qdfs]";
                    strSql += ",[qdzw]";
                    strSql += ",[cnzzxh]";
                    strSql += ",[dcrl]";
                    strSql += ",[zbzl]";
                    strSql += ",[zzl]";
                    strSql += ",[zj]";
                    strSql += ",[pqgsl]";
                    strSql += ",[pfjd])";
                    strSql += "VALUES";
                    strSql += "(";
                    strSql += "'" + vehicleRepository._vehiclemodel + "',";
                    strSql += "'" + vehicleRepository._sb + "',";
                    strSql += "'" + vehicleRepository._sccmc + "',";
                    strSql += "'" + vehicleRepository._sccdz + "',";
                    strSql += "'" + vehicleRepository._hdzkrs + "',";
                    strSql += "'" + vehicleRepository._bsxxs + "',";
                    strSql += "'" + vehicleRepository._qdfs + "',";
                    strSql += "'" + vehicleRepository._qdzw + "',";
                    strSql += "'" + vehicleRepository._cnzzxh + "',";
                    strSql += "'" + vehicleRepository._dcrl + "',";
                    strSql += "'" + vehicleRepository._zbzl + "',";
                    strSql += "'" + vehicleRepository._zzl + "',";
                    strSql += "'" + vehicleRepository._zj + "',";
                    strSql += "'" + vehicleRepository._pqgsl + "',";
                    strSql += "'" + vehicleRepository._pfjd + "')";

                    var vRet = DbHelper.ExecuteInsertSql(vConfig[0], strSql);
                    if (vRet.IsSuccess == false)
                    {
                        string SqlError = strSql;
                    }
                }
                else
                {
                    strSql = "UPDATE [VehicleRepository]";
                    strSql += " SET ";
                    strSql += " [sb] ='" + vehicleRepository._sb + "',";
                    strSql += " [sccmc] ='" + vehicleRepository._sccmc + "',";
                    strSql += " [sccdz] ='" + vehicleRepository._sccdz + "',";
                    strSql += " [hdzkrs] ='" + vehicleRepository._hdzkrs + "',";
                    strSql += " [bsxxs] ='" + vehicleRepository._bsxxs + "',";
                    strSql += " [qdfs] ='" + vehicleRepository._qdfs + "',";
                    strSql += " [qdzw] ='" + vehicleRepository._qdzw + "',";
                    strSql += " [cnzzxh] ='" + vehicleRepository._cnzzxh + "',";
                    strSql += " [dcrl] ='" + vehicleRepository._dcrl + "',";
                    strSql += " [zbzl] ='" + vehicleRepository._zbzl + "',";
                    strSql += " [zzl] ='" + vehicleRepository._zzl + "',";
                    strSql += " [zj] ='" + vehicleRepository._zj + "',";
                    strSql += " [pqgsl] ='" + vehicleRepository._pqgsl + "',";
                    strSql += " [pfjd] ='" + vehicleRepository._pfjd + "' ";
                    strSql += " where vehiclemodel='"+vehicleRepository._vehiclemodel+"'";

                    var vRet = DbHelper.ExecuteInsertSql(vConfig[0], strSql);
                    if (vRet.IsSuccess == false)
                    {
                        string SqlError = strSql;
                    }
                }
            }
            catch (Exception ex)
            {

            }
        }

        /// <summary>
        /// 得到车辆型号的信息
        /// </summary>
        /// <param name="reader"></param>
        /// <returns></returns>
        private VehicleRepository GetVehicleFromReader(IExcelDataReader reader)
        {
            VehicleRepository vehicleRepository = new VehicleRepository();
            try
            {
                vehicleRepository._vehiclemodel = reader.GetValue(1).ToString();
                vehicleRepository._sb = reader.GetValue(2).ToString();
                vehicleRepository._sccmc = reader.GetValue(3).ToString();
                vehicleRepository._sccdz = reader.GetValue(4).ToString();
                vehicleRepository._hdzkrs = reader.GetValue(5).ToString();
                vehicleRepository._bsxxs = reader.GetValue(6).ToString();
                vehicleRepository._qdfs = reader.GetValue(7).ToString();
                vehicleRepository._qdzw = reader.GetValue(8).ToString();
                vehicleRepository._cnzzxh = "";
                vehicleRepository._dcrl = "";
                vehicleRepository._zbzl = reader.GetValue(11).ToString();
                vehicleRepository._zzl = reader.GetValue(12).ToString();
                vehicleRepository._zj = reader.GetValue(13).ToString();
                vehicleRepository._pqgsl = reader.GetValue(14).ToString();
                vehicleRepository._pfjd = reader.GetValue(15).ToString();
            }
            catch (Exception ex)
            {

            }

            return vehicleRepository;
        }

        private void btnImportFDJ_Click(object sender, EventArgs e)
        {
            FileStream fs = null;
            try
            {
                string strTempPath = string.Empty;
                OpenFileDialog dialog = new OpenFileDialog();
                dialog.Multiselect = false;//该值确定是否可以选择多个文件
                dialog.Title = "请选择发动机模板库";
                dialog.Filter = "发动机模板库(*.xls,*.xlsx)|*.xls;*.xlsx";
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    strTempPath = dialog.FileName;

                    string strExt = Path.GetExtension(strTempPath);

                    IExcelDataReader excelReader = null;
                    fs = new FileStream(strTempPath, FileMode.Open, FileAccess.Read, FileShare.None);
                    if (strExt == ".xls")
                    {
                        excelReader = ExcelReaderFactory.CreateBinaryReader(fs);
                    }
                    else if (strExt == ".xlsx")
                    {
                        excelReader = ExcelReaderFactory.CreateOpenXmlReader(fs);
                    }

                    var vLst = new List<FdjRepository>();
                    int i = 0;
                    do
                    {
                        while (excelReader.Read())
                        {
                            if (i != 0)
                            {
                                var fdjRepository = GetFdjFromReader(excelReader);
                                vLst.Add(fdjRepository);
                            }
                            i++;
                        }
                    }
                    while (excelReader.NextResult());

                    for (int k = 0; k < vLst.Count; k++)
                    {
                        this.SaveFdjRepository(vLst[k]);
                    }

                    fs.Close();

                    MessageBox.Show("导入成功！");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
            }
            finally
            {
                if (fs != null)
                {
                    fs.Dispose();
                }
            }
        }

        /// <summary>
        /// 保存发动机的信息库
        /// </summary>
        /// <param name="fdjRepository"></param>
        private void SaveFdjRepository(FdjRepository fdjRepository)
        {
            try
            {
                var vConfig = Common.GetAppConfig();
                string strSql = "select count(*) from FdjRepository where fdjbs='" + fdjRepository._fdjbs + "'";

                string strValue = DbHelper.GetValue(vConfig[0], strSql);

                if (Convert.ToInt32(strValue) == 0)
                {
                    strSql = " INSERT INTO[dbo].[FdjRepository] ";
                    strSql += "(";
                    strSql += "[fdjbs]";
                    strSql += ",[fdjsb]";
                    strSql += ",[fdjsccdz]";
                    strSql += ",[rlzl]";
                    strSql += ",[edzs]";
                    strSql += ",[fdjpl]";
                    strSql += ",[edgl]";
                    strSql += ",[fdjqgs]";
                    strSql += ",[chzhqk])";
                    strSql += "VALUES";
                    strSql += "(";
                    strSql += "'" + fdjRepository._fdjbs + "',";
                    strSql += "'" + fdjRepository._fdjsb + "',";
                    strSql += "'" + fdjRepository._fdjsccdz + "',";
                    strSql += "'" + fdjRepository._rlzl + "',";
                    strSql += "'" + fdjRepository._edzs + "',";
                    strSql += "'" + fdjRepository._fdjpl + "',";
                    strSql += "'" + fdjRepository._edgl + "',";
                    strSql += "'" + fdjRepository._fdjqgs + "',";
                    strSql += "'" + fdjRepository._chzhqk + "')";

                    var vRet = DbHelper.ExecuteInsertSql(vConfig[0], strSql);
                    if (vRet.IsSuccess == false)
                    {
                        string SqlError = strSql;
                    }
                }
                else
                {
                    strSql = "UPDATE [FdjRepository]";
                    strSql += " SET ";
                    strSql += " [fdjsb] ='" + fdjRepository._fdjsb + "',";
                    strSql += " [fdjsccdz] ='" + fdjRepository._fdjsccdz + "',";
                    strSql += " [rlzl] ='" + fdjRepository._rlzl + "',";
                    strSql += " [edzs] ='" + fdjRepository._edzs + "',";
                    strSql += " [fdjpl] ='" + fdjRepository._fdjpl + "',";
                    strSql += " [edgl] ='" + fdjRepository._edgl + "',";
                    strSql += " [fdjqgs] ='" + fdjRepository._fdjqgs + "',";
                    strSql += " [chzhqk] ='" + fdjRepository._chzhqk + "' ";
                    strSql += " where fdjbs='" + fdjRepository._fdjbs + "'";

                    var vRet = DbHelper.ExecuteInsertSql(vConfig[0], strSql);
                    if (vRet.IsSuccess == false)
                    {
                        string SqlError = strSql;
                    }
                }
            }
            catch (Exception ex)
            {

            }
        }

        private FdjRepository GetFdjFromReader(IExcelDataReader reader)
        {
            FdjRepository fdjRepository = new FdjRepository();
            try
            {
                fdjRepository._fdjbs = reader.GetValue(1).ToString();
                fdjRepository._fdjsb= reader.GetValue(2).ToString();
                fdjRepository._fdjsccdz = reader.GetValue(3).ToString();
                fdjRepository._rlzl = reader.GetValue(4).ToString();
                fdjRepository._edzs = reader.GetValue(5).ToString();
                fdjRepository._fdjpl = reader.GetValue(6).ToString();
                fdjRepository._edgl = reader.GetValue(7).ToString();
                fdjRepository._fdjqgs = reader.GetValue(8).ToString();
                fdjRepository._chzhqk = reader.GetValue(9).ToString();
            }
            catch (Exception ex)
            {

            }

            return fdjRepository;
        }

        /// <summary>
        /// 绑定车型信息
        /// </summary>
        /// <param name="strKey"></param>
        private void BindVehicleInfo(string strKey)
        {
            try
            {
                this.dgVehicleRepo.DataSource = null;

                string strSql = "select ID, vehiclemodel,zzl,zbzl,pfjd from VehicleRepository";

                if(string.IsNullOrEmpty(strKey) == false)
                {
                    strSql += " where vehiclemodel like '%" + strKey + "%'";
                }

                var vConfig = Common.GetAppConfig();

                DataTable dt = new DataTable();
                DbHelper.GetTable(vConfig[0], strSql, ref dt);

                this.dgVehicleRepo.DataSource = dt;

                lblVCount.Text = dt.Rows.Count.ToString();

                SetDataGridViewStyle();
            }
            catch(Exception ex)
            {

            }
        }

        private void SetDataGridViewStyle()
        {
            dgVehicleRepo.Columns["ID"].HeaderText = "ID";
            dgVehicleRepo.Columns["vehiclemodel"].HeaderText = "车辆型号";
            dgVehicleRepo.Columns["zzl"].HeaderText = "总质量";
            dgVehicleRepo.Columns["zbzl"].HeaderText = "整备质量";
            dgVehicleRepo.Columns["pfjd"].HeaderText = "排放阶段";

            dgVehicleRepo.Columns["ID"].FillWeight = 40;
            dgVehicleRepo.Columns["vehiclemodel"].FillWeight = 120;
            dgVehicleRepo.Columns["zzl"].FillWeight = 100;
            dgVehicleRepo.Columns["zbzl"].FillWeight = 100;
            dgVehicleRepo.Columns["pfjd"].FillWeight = 100;

            dgVehicleRepo.Columns["ID"].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgVehicleRepo.Columns["vehiclemodel"].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgVehicleRepo.Columns["zzl"].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgVehicleRepo.Columns["zbzl"].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgVehicleRepo.Columns["pfjd"].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;

            dgVehicleRepo.Columns["ID"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgVehicleRepo.Columns["vehiclemodel"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgVehicleRepo.Columns["zzl"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgVehicleRepo.Columns["zbzl"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgVehicleRepo.Columns["pfjd"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

            dgVehicleRepo.Columns["ID"].SortMode = DataGridViewColumnSortMode.NotSortable;
            dgVehicleRepo.Columns["vehiclemodel"].SortMode = DataGridViewColumnSortMode.NotSortable;
            dgVehicleRepo.Columns["zzl"].SortMode = DataGridViewColumnSortMode.NotSortable;
            dgVehicleRepo.Columns["zbzl"].SortMode = DataGridViewColumnSortMode.NotSortable;
            dgVehicleRepo.Columns["pfjd"].SortMode = DataGridViewColumnSortMode.NotSortable;
        }

        private void btnDelR_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.dgVehicleRepo.SelectedRows.Count == 0)
                {
                    MessageBox.Show("请选中要删除的车辆！");
                    return;
                }

                if (MessageBox.Show("确认删除？", "此删除不可恢复", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    string strID = this.dgVehicleRepo.SelectedRows[0].Cells[0].Value.ToString();

                    if (string.IsNullOrEmpty(strID) == false)
                    {
                        string strSql = "delete from VehicleRepository where ID='" + strID + "'";

                        var vConfig = Common.GetAppConfig();
                        bool bDel = DbHelper.ExecuteSql(vConfig[0],strSql);

                        if (bDel)
                        {
                            MessageBox.Show("删除成功！");
                        }
                        else
                        {
                            MessageBox.Show("删除失败！");
                        }

                        btnSearch_Click(sender, e);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("删除失败！" + ex.Message);
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            try
            {
                if (MessageBox.Show("确认清除所有的车辆型号？", "此清除不可恢复", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    string strID = this.dgVehicleRepo.SelectedRows[0].Cells[0].Value.ToString();

                    if (string.IsNullOrEmpty(strID) == false)
                    {
                        string strSql = "delete from VehicleRepository";

                        var vConfig = Common.GetAppConfig();
                        bool bDel = DbHelper.ExecuteSql(vConfig[0], strSql);

                        if (bDel)
                        {
                            MessageBox.Show("清除成功！");
                        }
                        else
                        {
                            MessageBox.Show("清除失败！");
                        }

                        btnSearch_Click(sender, e);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("清除失败！" + ex.Message);
            }
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            try
            {
                string strSql = "select * from VehicleRepository";
                var vConfig = Common.GetAppConfig();

                DataTable dt = new DataTable();
                DbHelper.GetTable(vConfig[0], strSql, ref dt);

                SaveFileDialog myDialog = new SaveFileDialog();

                string strFileName = "车型库";

                // Default file name
                myDialog.FileName = strFileName;

                // Default file extension
                myDialog.DefaultExt = ".xls";

                // Filter files by extension
                myDialog.Filter = "车型库 (.xls)|*.xls";

                var result = myDialog.ShowDialog();

                if (result == DialogResult.Yes || result == DialogResult.OK)
                {
                    //文件名
                    string filename = myDialog.FileName;

                    Microsoft.Office.Interop.Excel.Application curExcel = new Excel.Application();

                    int rowIndex = 1;
                    int colIndex = 0;

                    curExcel.Application.Workbooks.Add(true);

                    System.Data.DataTable table = dt;
                    foreach (DataColumn col in table.Columns)
                    {
                        colIndex++;
                        curExcel.Cells[1, colIndex] = col.ColumnName;
                    }

                    foreach (DataRow row in table.Rows)
                    {
                        rowIndex++;
                        colIndex = 0;
                        foreach (DataColumn col in table.Columns)
                        {
                            colIndex++;
                            curExcel.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();
                        }

                        lblExport.Text = "正在导出,导出" + (rowIndex-1) + "条";
                    }

                    lblExport.Text = "导出完成,共导出" + (rowIndex - 1) + "条";
                    curExcel.Visible = false;
                    curExcel.ActiveWorkbook.SaveAs(filename, Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel8, null, null, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, null, null, null, null);
                    curExcel.Quit();
                    curExcel = null;

                    GC.Collect();//垃圾回收

                    MessageBox.Show("导出模版成功！");
                }

            }
            catch(Exception ex)
            {

            }
        }

        private void btnSearchFDJ_Click(object sender, EventArgs e)
        {
            string strKey = txtFDJBS.Text.Trim();

            BindFdjInfo(strKey);
        }

        /// <summary>
        /// 绑定发动机信息.
        /// </summary>
        /// <param name="strKey"></param>
        private void BindFdjInfo(string strKey)
        {
            try
            {
                this.dgFDJ.DataSource = null;

                string strSql = "select ID, fdjbs,fdjsb,rlzl,edzs from FdjRepository";

                if (string.IsNullOrEmpty(strKey) == false)
                {
                    strSql += " where fdjbs like '%" + strKey + "%'";
                }

                var vConfig = Common.GetAppConfig();

                DataTable dt = new DataTable();
                DbHelper.GetTable(vConfig[0], strSql, ref dt);

                this.dgFDJ.DataSource = dt;

                lblFCount.Text = dt.Rows.Count.ToString();

                SetDataGridViewStyleFDJ();
            }
            catch (Exception ex)
            {

            }
        }

        private void SetDataGridViewStyleFDJ()
        {
            dgVehicleRepo.Columns["ID"].HeaderText = "ID";
            dgVehicleRepo.Columns["fdjbs"].HeaderText = "发动机标识";
            dgVehicleRepo.Columns["fdjsb"].HeaderText = "发动机商标";
            dgVehicleRepo.Columns["rlzl"].HeaderText = "燃料种类";
            dgVehicleRepo.Columns["edzs"].HeaderText = "额定转速";

            dgVehicleRepo.Columns["ID"].FillWeight = 40;
            dgVehicleRepo.Columns["fdjbs"].FillWeight = 120;
            dgVehicleRepo.Columns["fdjsb"].FillWeight = 100;
            dgVehicleRepo.Columns["rlzl"].FillWeight = 100;
            dgVehicleRepo.Columns["edzs"].FillWeight = 100;

            dgVehicleRepo.Columns["ID"].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgVehicleRepo.Columns["vehiclemodel"].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgVehicleRepo.Columns["fdjsb"].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgVehicleRepo.Columns["rlzl"].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgVehicleRepo.Columns["edzs"].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;

            dgVehicleRepo.Columns["ID"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgVehicleRepo.Columns["vehiclemodel"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgVehicleRepo.Columns["fdjsb"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgVehicleRepo.Columns["rlzl"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgVehicleRepo.Columns["edzs"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

            dgVehicleRepo.Columns["ID"].SortMode = DataGridViewColumnSortMode.NotSortable;
            dgVehicleRepo.Columns["vehiclemodel"].SortMode = DataGridViewColumnSortMode.NotSortable;
            dgVehicleRepo.Columns["fdjsb"].SortMode = DataGridViewColumnSortMode.NotSortable;
            dgVehicleRepo.Columns["rlzl"].SortMode = DataGridViewColumnSortMode.NotSortable;
            dgVehicleRepo.Columns["edzs"].SortMode = DataGridViewColumnSortMode.NotSortable;
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(tabControl1.SelectedIndex == 1)
            {
                btnSearchFDJ_Click(sender, e);
            }
        }

        private void btnViewFDJ_Click(object sender, EventArgs e)
        {
            if (dgFDJ.SelectedRows.Count == 0)
            {
                MessageBox.Show("请选中要查看的车辆型号！");
                return;
            }

            string strID = dgFDJ.SelectedRows[0].Cells[0].Value.ToString();

            if (string.IsNullOrEmpty(strID) == false)
            {
                FrmFDJInfo frmFDJInfo = new FrmFDJInfo("View", strID);
                frmFDJInfo.ShowDialog();
            }
        }

        private void btnAddFDJ_Click(object sender, EventArgs e)
        {
            FrmFDJInfo frmFDJInfo = new FrmFDJInfo("Add", "");
            frmFDJInfo.ShowDialog();
        }

        private void btnUpdateFDJ_Click(object sender, EventArgs e)
        {
            if (dgFDJ.SelectedRows.Count == 0)
            {
                MessageBox.Show("请选中要修改的发动机信息！");
                return;
            }

            string strID = dgFDJ.SelectedRows[0].Cells[0].Value.ToString();

            if (string.IsNullOrEmpty(strID) == false)
            {
                FrmFDJInfo frmFDJInfo = new FrmFDJInfo("Update", strID);
                frmFDJInfo.ShowDialog();
            }
        }

        private void btnDelFDJ_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.dgFDJ.SelectedRows.Count == 0)
                {
                    MessageBox.Show("请选中要删除的发动机信息！");
                    return;
                }

                if (MessageBox.Show("确认删除？", "此删除不可恢复", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    string strID = this.dgFDJ.SelectedRows[0].Cells[0].Value.ToString();

                    if (string.IsNullOrEmpty(strID) == false)
                    {
                        string strSql = "delete from FdjRepository where ID='" + strID + "'";

                        var vConfig = Common.GetAppConfig();
                        bool bDel = DbHelper.ExecuteSql(vConfig[0], strSql);

                        if (bDel)
                        {
                            MessageBox.Show("删除成功！");
                        }
                        else
                        {
                            MessageBox.Show("删除失败！");
                        }

                        btnSearchFDJ_Click(sender, e);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("删除失败！" + ex.Message);
            }
        }

        private void btnExportFDJ_Click(object sender, EventArgs e)
        {
            try
            {
                string strSql = "select * from FdjRepository";
                var vConfig = Common.GetAppConfig();

                DataTable dt = new DataTable();
                DbHelper.GetTable(vConfig[0], strSql, ref dt);

                SaveFileDialog myDialog = new SaveFileDialog();

                string strFileName = "发动机信息库";

                // Default file name
                myDialog.FileName = strFileName;

                // Default file extension
                myDialog.DefaultExt = ".xls";

                // Filter files by extension
                myDialog.Filter = "车型库 (.xls)|*.xls";

                var result = myDialog.ShowDialog();

                if (result == DialogResult.Yes || result == DialogResult.OK)
                {
                    //文件名
                    string filename = myDialog.FileName;

                    Microsoft.Office.Interop.Excel.Application curExcel = new Excel.Application();

                    int rowIndex = 1;
                    int colIndex = 0;

                    curExcel.Application.Workbooks.Add(true);

                    System.Data.DataTable table = dt;
                    foreach (DataColumn col in table.Columns)
                    {
                        colIndex++;
                        curExcel.Cells[1, colIndex] = col.ColumnName;
                    }

                    foreach (DataRow row in table.Rows)
                    {
                        rowIndex++;
                        colIndex = 0;
                        foreach (DataColumn col in table.Columns)
                        {
                            colIndex++;
                            curExcel.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();
                        }

                        lblExportF.Text = "正在导出,导出" + (rowIndex - 1) + "条";
                    }

                    lblExportF.Text = "导出完成,共导出" + (rowIndex - 1) + "条";
                    curExcel.Visible = false;
                    curExcel.ActiveWorkbook.SaveAs(filename, Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel8, null, null, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, null, null, null, null);
                    curExcel.Quit();
                    curExcel = null;

                    GC.Collect();//垃圾回收

                    MessageBox.Show("导出发动机模版成功！");
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("导出发动机模版失败！" + ex.Message);
            }
        }

        private void btnClearFDJ_Click(object sender, EventArgs e)
        {
            try
            {
                if (MessageBox.Show("确认清除所有的发动机信息？", "此清除不可恢复", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    string strID = this.dgFDJ.SelectedRows[0].Cells[0].Value.ToString();

                    if (string.IsNullOrEmpty(strID) == false)
                    {
                        string strSql = "delete from FdjRepository";

                        var vConfig = Common.GetAppConfig();
                        bool bDel = DbHelper.ExecuteSql(vConfig[0], strSql);

                        if (bDel)
                        {
                            MessageBox.Show("清除成功！");
                        }
                        else
                        {
                            MessageBox.Show("清除失败！");
                        }

                        btnSearchFDJ_Click(sender, e);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("清除失败！" + ex.Message);
            }
        }
    }
}
